package lark

import (
	"code.bydev.io/frameworks/byone/rest/httpc"
	"context"
	"fmt"
	"net/http"
	"strings"

	"emperror.dev/errors"
	"git.bybit.com/svc/mod/pkg/opsalarm"
)

type LarkRaiser = *impl

type impl struct {
	u string
}

type message struct {
	MsgType string `json:"msg_type"`
	Content struct {
		Text string `json:"text"`
	} `json:"content"`
}

func New(url string) *impl {
	return &impl{u: url}
}

var _ opsalarm.Raiser = (*impl)(nil)

func (i *impl) Raise(ctx context.Context, alarm *opsalarm.Alarm) error {
	msg := message{
		MsgType: "text",
		Content: struct {
			Text string `json:"text"`
		}{
			Text: format(alarm),
		},
	}
	_, err := httpc.Do(context.Background(), http.MethodPost, i.u, msg)
	return errors.Wrap(err, "larkraiser.Raise")
}

func format(alarm *opsalarm.Alarm) string {
	sb := new(strings.Builder)
	if alarm.Environment != "" {
		ignore(fmt.Fprintf(sb, "### %s\n", alarm.Environment))
	}
	sb.WriteString(alarm.Text)
	if len(alarm.Attributes) > 0 {
		sb.WriteString("\n\n")
		for k, v := range alarm.Attributes {
			ignore(sb.WriteRune('\n'))
			ignore(fmt.Fprintf(sb, "- *%s*: %s", k, v))
		}
	}

	return sb.String()
}

func ignore(int, error) {}
